
<?php

	class dbini extends ini{
		
		var $critical_keys = array('user', 'pass', 'name', 'type', 'host', 'keylen', 'keypad');
		
		function __construct($DOM, $data = array('type'=>'mysql', 'host'=>'localhost', 'keylen'=>1, 'keypad'=>'_'), $readonly=true){
			$this->_set('DOM', $DOM);
			parent::__construct(ETC_DIR.'/db/'.$DOM, $data, $readonly);
		}
		
		function open_abstractor(){
			return sn()->call_abstractor($this->type, $this->user, $this->pass, $this->name, $this->host);	
		}
		
		function domain(){
			return Domain($this->_get('DOM'));	
		}
		
		function build_settings(){
			$this->_set('readonly', true);
			
			// package settings
			$this->packages = new obj;
			
			// real table names that link to packages
			$this->tables = new obj;
			
			// real key names that link to real tables
			$this->keys = new obj;
			
			foreach($this as $package_table => $table_settings){
				
				// if it ain't an array it ain't table settings
				if(!is_array($table_settings)) continue;
				$empty = empty($table_settings);
				// We're gonna split the string e.g. MyPackage/v0.1/mytable
				$a = explode('/', $package_table);
				// Name of package (mypackage)
				$package_name = strtolower($a[0]);
				// table name according to package (mytable)
				if(!$empty) $package_table = array_pop($a);
				// Path to package (MyPackage/v0.1)
				$package_path = implode('/', $a);
			
				// Set up package obj if not yet set $this->pkgs->MyPackage
				if(!$this->package_data($package_name)) $this->add_package($package_name, $package_path);
				if($empty) continue;
				// Object Recursion Ahoy!!! 
				$table_settings['package'] = $this->package_data($package_name);
				
				// key name (m is now e.g. m_)
				$table_settings['key'] = str_pad($table_settings['key'], $this->keylen, $this->keypad);
				
				// $package->tables->mytable = the ini settings, including a link to the package obj
				$table_settings['package']->tables->$package_table = new obj($table_settings);
				
				// Keys to tables obj for benefit of Package, once it's instantiated : $package->keys->mytable = 'm_'
				$table_settings['package']->keys->$package_table = $table_settings['key'];
				
				// Tables to packages, but actual name of table in db : $this->tables->realtablename
				$this->tables->$table_settings['name'] = $table_settings['package'];
				
				// Keys to tables for benefit of this dbobject : $this->keys->m_ = realtablename
				$this->keys->$table_settings['key'] = $table_settings['name'];
			}
		}
		
		function package_data($name){
			return $this->packages->get(strtolower($name));
		}
		
		function add_package($name, $path){
			$this->packages->set($name, new obj(
				'name',			$name,
				'path',			$path,
				'namespace',	alphanum($path),
				'tables',		new obj,
				'keys',			new obj,
				// where the instantiated package shall live
				'Package',		false
			));
		}
	}


